package com.ceba.be.api.utils;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URLDecoder;

/**
 * Created by liguangyao on 3/11/2020.
 */

/**
 * 简单的http服务器
 */
public class TestHttpServer {
    public static void main(String[] args) {
        try {
            HttpServer server = HttpServer.create(new InetSocketAddress(8081), 0);//监听8080端口，第二个参数小于等于0使用默认值，表示可同时接受请求的个数
            server.createContext("/test", new AccessSignedFileHandler());
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取签章系统回传回来的签名文件地址
     */
    static class AccessSignedFileHandler implements HttpHandler {

        public void handle(HttpExchange exchange) throws IOException {
            System.out.println("getRequestMethod:" + exchange.getRequestMethod());//请求方法GET、POST

            URI uri = exchange.getRequestURI();
            System.out.println("uri.getRawPath:" + uri.getRawPath());
            System.out.println("uri.getRawQuery:" + uri.getRawQuery());

            String rawQuery = uri.getRawQuery();
            if (rawQuery.startsWith("json=")) {
                rawQuery = rawQuery.replace("json=", "");

                rawQuery = URLDecoder.decode(rawQuery, "utf-8");
                BASE64Decoder base64Decoder = new BASE64Decoder();
                rawQuery = new String(base64Decoder.decodeBuffer(rawQuery), "utf-8");
                System.out.println(rawQuery);
                System.out.println("成功解析IDS服务器发送数据！");
            } else {
                System.out.println("无法解析，IDS服务器发送数据错误！");
            }

            exchange.sendResponseHeaders(200, 0);
            System.out.println("ResponseCode:" + exchange.getResponseCode());
            exchange.close();
        }

    }

}
